package com.lianqi.emcpframework.shiro.cas.util;

import java.util.Date;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.pac4j.cas.client.rest.CasRestFormClient;
import org.pac4j.cas.profile.CasProfile;
import org.pac4j.cas.profile.CasRestProfile;
import org.pac4j.core.context.J2EContext;
import org.pac4j.core.credentials.TokenCredentials;
import org.pac4j.core.profile.CommonProfile;
import org.pac4j.core.profile.ProfileManager;
import org.pac4j.jwt.profile.JwtGenerator;

/**
 * @program emcp-portal
 * @ClassName JwtTokenUtils
 * @description: jwt 认证token 工具类
 * @author: sky
 * @create: 2019/05/16 16:21
 */
public class JwtTokenUtils {

    public static final int DELAYED = 1 * 60 * 1000;

    public static final String JWT_TOKEN = "jwtToken";

    /**
     * 生成jwtToken
     * 
     * @param request
     * @param response
     * @param restFormClient
     *            rest 客户端
     * @param generator
     *            jwtToken生成器
     * @param serviceUrl
     *            当前服务url
     * @param expireTime
     *            延迟时间
     * @return
     */
    public static String provideJwtToken(HttpServletRequest request, HttpServletResponse response,
        CasRestFormClient restFormClient, JwtGenerator generator, String serviceUrl, Long expireTime) {
        J2EContext context = new J2EContext(request, response);
        final ProfileManager<CasRestProfile> profileManager = new ProfileManager(context);
        final Optional<CasRestProfile> profile = profileManager.get(true);
        // 获取ticket
        TokenCredentials ticket = restFormClient.requestServiceTicket(serviceUrl, profile.get(), context);
        // 通过ticket获取登录用户信息
        final CasProfile casProfile = restFormClient.validateServiceTicket(serviceUrl, ticket, context);
        return provideJwtToken(casProfile, generator, expireTime);
    }

    /**
     * 生成jwtToken
     * 
     * @param profile
     *            登录用户相关信息
     * @param generator
     *            jwtToken 生成器
     * @param expireTime
     *            延迟时间
     * @return
     */
    public static String provideJwtToken(CommonProfile profile, JwtGenerator generator, Long expireTime) {
        Long expirationTime = System.currentTimeMillis() + expireTime + DELAYED;
        // 生成jwt token
        generator.setExpirationTime(new Date(expirationTime));
        return generator.generate(profile);
    }
}
